package com.datasecops.scannerservices.db;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;

import javax.swing.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: GeXiaoLong
 * @time: 2022/10/20 10:31
 */
public class ESClient {
    //无密码登录
    public static RestHighLevelClient getClient(String ip,int post){
        // 创建HttpHost对象
        HttpHost httpHost = new HttpHost(ip,post);

        // 创建RestClientBuilder
        RestClientBuilder clientBuilder = RestClient.builder(httpHost);

        // 创建RestHighLevelClient
        RestHighLevelClient client = new RestHighLevelClient(clientBuilder);

        // 返回
        return client;
    }

    //有密码登录
    public static RestHighLevelClient client(String ip,int post,String userName, String password) {
        RestHighLevelClient esClient = null;

        final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName,password ));
        esClient =  new RestHighLevelClient(RestClient.builder(
                        new HttpHost(ip,post))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    public HttpAsyncClientBuilder customizeHttpClient(
                            HttpAsyncClientBuilder httpClientBuilder) {
                        httpClientBuilder.disableAuthCaching();
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                })
        );
        return esClient;
    }
     /**
      *获取索引
      * @Description
      * @author GeXiaoLong
      * @time 2022/10/21 9:18
      * @param
      * @return
      */
    public static List<String> getAllCollections(String Instance ) {
        List<String> list = new ArrayList<>();
        list.add(Instance+".1");
        return list;
    }

}



